package com.stox.ui.swing.widget;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.UIManager;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stox.ui.swing.util.ImageIconLoader;
import com.stox.ui.swing.util.SwingUtil;

@Component
public class MainFrame  extends JFrame implements InitializingBean{
	private static final long serialVersionUID = 1L;

	private static MainFrame instance;
	
	@Autowired
	private MainDesktop desktop;
	
	@Autowired
	private MessagePanel messagePanel;
	
	@Autowired
	private MenuBar menuBar;

	public static MainFrame getInstance(){
		return instance;
	}
	
	public MainFrame() {
		super("Stockz");
		if(null != instance){
			throw new UnsupportedOperationException();
		}
		instance = this;
		setLookAndFeel();
		setSize();
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
		setJMenuBar(menuBar);
		add(desktop,BorderLayout.CENTER);
		add(messagePanel, BorderLayout.SOUTH);
	}
	
	private void setLookAndFeel(){
		setIconImage(ImageIconLoader.loadImage("icon.jpg"));
		setLookAndFeel(0, new String[]{
				"javax.swing.plaf.nimbus.NimbusLookAndFeel",
				"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"});
	}
	
	private void setLookAndFeel(int pointer, String[] lafs){
		try{
			if(pointer < lafs.length){
				UIManager.setLookAndFeel(lafs[pointer]);
			}
		}catch(Exception cnfe){
			cnfe.printStackTrace();
			setLookAndFeel(++pointer, lafs);
		}
	}
	
	
	private void setSize(){
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Rectangle maxBounds = SwingUtil.getScreenSize();
        setMaximizedBounds(maxBounds);
        Dimension maxDimension = new Dimension(maxBounds.width/3,maxBounds.height/3);
        setMaximumSize(maxDimension);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
		setPreferredSize(maxDimension);
	}

	public MessagePanel getMessagePanel(){
		return messagePanel;
	}
	
	public MainDesktop getDesktop() {
		return desktop;
	}
		
}
